<template>
  <div class="register-form">
    <h2 class="register-title">用户注册</h2>
    <el-form :model="registerForm" ref="registerFormRef" :rules="rules">
      <el-form-item prop="username">
        <el-input
          v-model="registerForm.username"
          placeholder="请输入用户名"
          prefix-icon="User"
        />
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="registerForm.password"
          type="password"
          placeholder="请输入密码"
          prefix-icon="Lock"
          show-password
        />
      </el-form-item>
      <el-form-item prop="confirmPassword">
        <el-input
          v-model="registerForm.confirmPassword"
          type="password"
          placeholder="请确认密码"
          prefix-icon="Lock"
          show-password
        />
      </el-form-item>
      <el-form-item prop="code">
        <div class="captcha-container">
          <el-input
            v-model="registerForm.code"
            placeholder="请输入验证码"
            prefix-icon="Key"
          />
          <img 
            :src="captchaUrl" 
            @click="refreshCaptcha" 
            alt="验证码"
            class="captcha-img"
          >
        </div>
      </el-form-item>
      <el-form-item>
        <el-button 
          type="primary" 
          class="register-button" 
          :loading="loading"
          @click="handleSubmit"
        >
          {{ loading ? '注册中...' : '注册' }}
        </el-button>
      </el-form-item>
    </el-form>

  </div>
</template>

<!-- <script lang="ts">
import { defineComponent, reactive, ref, onMounted } from 'vue'
import {  FormRules } from 'element-plus'
// import { ElMessage,  } from 'element-plus'
// import {  FormInstance} from 'element-plus'
// import request from '@/utils/request'

export default defineComponent({
  name: 'RegisterModal',
  emits: ['switch-to-login', 'register-success'],
  setup(props, { emit }) {
    const loading = ref(false)
    const registerFormRef = ref()
    
    const registerForm = reactive({
      username: '',
      password: '',
      confirmPassword: '',
      code: '',
      uuid: ''
    })

    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== registerForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }

    const rules = reactive<FormRules>({
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请再次输入密码', trigger: 'blur' },
        { validator: validatePass2, trigger: 'blur' }
      ],
      code: [
        { required: true, message: '请输入验证码', trigger: 'blur' }
      ]
    })

    const captchaUrl = ref('')

    // const getCaptcha = async () => {
    //   try {
    //     const res = await request.get('/captchaImage')
    //     if (res.code === 200) {
    //       captchaUrl.value = 'data:image/gif;base64,' + res.img
    //       registerForm.uuid = res.uuid
    //     }
    //   } catch (error) {
    //     console.error('获取验证码失败:', error)
    //   }
    // }

    // const refreshCaptcha = () => {
    //   getCaptcha()
    // }

    // const handleSubmit = async () => {
    //   if (!registerFormRef.value) return
      
    //   await registerFormRef.value.validate(async (valid) => {
    //     if (valid) {
    //       loading.value = true
    //       try {
           
    //         const res = await request.post('/register', submitForm)
    //         if (res.code === 200) {
    //           ElMessage.success('注册成功')
    //           emit('register-success')
    //           emit('switch-to-login')
    //         }
    //       } catch (error) {
    //         console.error('注册失败:', error)
    //         refreshCaptcha()
    //       } finally {
    //         loading.value = false
    //       }
    //     }
    //   })
    // }

    const handleBackToLogin = () => {
      emit('switch-to-login')
    }

    onMounted(() => {
      getCaptcha()
    })

    return {
      registerForm,
      registerFormRef,
      rules,
      loading,
      captchaUrl,
      handleSubmit,
      refreshCaptcha,
      handleBackToLogin
    }
  }
})
</script> -->

<script setup>
import {   ref,onMounted,defineModel} from 'vue'
import {captcha,register} from '@/api/auth'
const loading = ref(false)

const flag = defineModel()

    const registerForm = ref({
      username: '',
      password: '',
      confirmPassword: '',
      code: '',
      uuid: ''
    })

    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== registerForm.value.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }

    const rules = ref({
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请再次输入密码', trigger: 'blur' },
        { validator: validatePass2, trigger: 'blur' }
      ],
      code: [
        { required: true, message: '请输入验证码', trigger: 'blur' }
      ]
    })

    const getCaptcha1 = async () => {
  //  const res = await captcha()
  // console.log(res+'6');
  const res = await captcha()
  console.log(res);
  if (res.data.code === 200) {
      captchaUrl.value = 'data:image/gif;base64,' + res.data.img
      registerForm .value.uuid = res.data.uuid
    }
   
 }

 const captchaUrl = ref('')


// 刷新验证码
const refreshCaptcha = () => {
      getCaptcha1()
    }

 onMounted(() => {
      getCaptcha1()
    })

    
//登录1.校验2.发请求
const registerFormRef = ref(null)
const handleSubmit = async()=>{
  await registerFormRef.value.validate();
  console.log('通过');
      
const res = await register(registerForm.value)
console.log(res);

if (res.data.code === 200) {
  console.log(11);

  ElMessage.success('注册成功')
  // 注册成功，跳转到登录
 flag.value=!flag.value


  
}
  }
</script>
<style scoped>
.register-form {
  padding: 30px;
}

.register-title {
  text-align: center;
  font-size: 24px;
  color: #333;
  margin-bottom: 30px;
}

.captcha-container {
  display: flex;
  gap: 12px;
  align-items: center;
}

.captcha-img {
  height: 40px;
  cursor: pointer;
  border-radius: 4px;
}

.register-button {
  width: 100%;
  height: 40px;
  font-size: 16px;
}

.login-section {
  text-align: center;
  margin-top: 16px;
  color: #666;
}

.login-text {
  font-size: 14px;
  margin-right: 4px;
}

.login-link {
  font-size: 14px;
  padding: 0 4px;
}

:deep(.login-link.el-button) {
  font-weight: 600;
}

:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px var(--el-color-primary) inset;
}

:deep(.el-form-item__error) {
  color: #f56c6c;
}
</style> 